/*
 CLEditor YouTube Plugin v1.0.0
 http://www.terapix.de
 requires jQuery v1.4.2 or later, CLEditor WYSIWYG HTML Editor v1.3.0 or later

 Copyright 2012, Markus Horowski, TeraPix.de
 Licensed GPL Version 3 licenses.
*/

(function($)
{
	// Define the vimeo/youtube button
	$.cleditor.buttons.youtube = {
		name: "youtube",
		image: "youtube.png",
		title: "YouTube Video",
		command: "inserthtml",
    popupName: "youtube",
    popupClass: "cleditorPrompt",
    popupContent:
      "<table cellpadding=0 cellspacing=0><tr>" +
      "<td>YouTube URL:<br><input type=text style='width:200px;'>" +
      "<br>or Vimeo URL:<br><input type=text style='width:200px;'></td>" +
      "</tr></table><input type=button value='Insert video'>",
    buttonClick: youtubeButtonClick
  };

  // Event handler
  function youtubeButtonClick(e, data) {

    // Listen to submitting the button
    $(data.popup).children(":button")
      .unbind("click")
      .bind("click", function(e) {

        // Get the editor
        var editor = data.editor;

        // Get the first text-input value
        var $text = $(data.popup).find(":text"),
          videourl = decodeURI($text[0].value);

        // If first value is set, write youtube embed-code
        if(videourl.length)
        {
          var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
	        var match = videourl.match(regExp);

          if (match&&match[7].length==11)
          {
            var videourl = match[7];
            var html = '<iframe title="YouTube Video Player" class="youtube-player" type="text/html" width="570" height="321" src="http://www.youtube.com/embed/' + videourl + '?rel=0" frameborder="0" wmode="transparant"></iframe>';
          }
        }

        // Get the second text-input value
        var $text = $(data.popup).find(":text"),
          vimeourl = decodeURI($text[1].value);

        // If second value is set, write vimeo embed-code
        if(vimeourl.length)
        {
          var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;
          var match = vimeourl.match(regExp);

          if (match){
            vimeourl = match[2];
            var html = '<iframe src="http://player.vimeo.com/video/' + vimeourl + '?color=ffffff" width="570" height="320" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
          }
        }

        // Insert the html into the editor
        if (html)
          editor.execCommand(data.command, html, null, data.button);

        // Hide the popup and set the focus
        editor.hidePopups();
        editor.focus();
      });
  }
})(jQuery);